<template>
	<div class="ai-template-view-wrapper" :class="`${videoType}-${audioType}`" v-if="showTemplate">
		<el-drawer :visible.sync="showTemplate" direction="rtl" custom-class="ai-template-wrapper-container" :destroy-on-close="true" :before-close="onClose" :modal="false" :size="'600px'">
			<div slot="title" class="dialog-title">
				<AiTemplateTitle
					:taskId="taskId"
					:name="form.name"
					:showDetail="showDetail"
					:associatedVariable="form.associatedVariable"
					@updateTitleName="updateTitleName"
					@onAssociatedVariableClick="onAssociatedVariableClick"
					ref="aiTemplateTitle"
				/>
			</div>
			<TemplateForm
				:form="form"
				:nextStepOption="nextStepOption"
				:showTemplate="showTemplate"
				:showDetail="showDetail"
				@showVideoTable="showVideoTable"
				:taskId="taskId"
				@input="input"
				@onChange="onChange"
				@settingClick="settingClick"
				@onSettingQuestion="onSettingQuestion"
				@onAddVariable="onAddVariable"
				@chooseUserAttribute="chooseUserAttribute"
				@clearVideo="clearVideo"
				ref="templateForm"
				:agentNameError="agentNameError"
				:nluError="nluError"
				:returnParametersError="returnParametersError"
				:requestParametersError="requestParametersError"
			/>
			<div class="dialog-footer">
				<el-button @click="onClose" v-if="!showDetail">取消</el-button>
				<el-button type="primary" class="btn-blue" @click="onOk" v-if="!showDetail">保存</el-button>
			</div>
		</el-drawer>
		<!-- 智能问答 -->
		<SettingQuestion
			@changePageSize="changePageSize"
			:showDetail="showDetail"
			@changeCurrentPage="changeCurrentPage"
			:questionData="questionData"
			@saveSelectQuestion="saveCheckQuestion"
			:dialogTableVisible="showQuestionSetting"
			:selectedReply="selectedReply"
			@close="questionClose"
			:pages="questionPages"
			ref="settingQuestion"
		/>
		<AnswerNlu
			v-if="isShowAnswerNlu"
			:dialogVisible="isShowAnswerNlu"
			:answerNluMode="answerNluMode"
			:answerNluData="form[nluProp]"
			:prop="nluProp"
			:nluError="nluError"
			@input="input"
			:showDetail="showDetail"
			@delAnswerNluKeys="delAnswerNluKeys"
			@addAnswerNluKey="addAnswerNluKey"
			@answerNluKeyBlur="answerNluKeyBlur"
			@close="closeAnserNlu"
			@down="downloadNluKeys('common-verification', answerNluMode)"
			@submit="submitNluKeys"
		/>
		<!-- 用户变量 -->
		<UserAttribute v-if="isShowUserAttribute" :dialogVisible="isShowUserAttribute" :taskId="taskId" @on-ok="onChosseUserAttribute" @on-cancel="onCloseUserAttribute" />
		<!-- 视频表格 -->
		<VideoTable
			v-if="tableVideoDialog"
			:tableVideoDialog="tableVideoDialog"
			:videoType="tableVideoType"
			:videoSlect="selectVideoIndex[arrayVideoIdx]"
			@ok="sureVideoData"
			@cancel="cancelVideoData"
			:showDetail="showDetail"
		/>
		<!-- 关联变量 -->
		<AssociatedVariableTable
			v-if="showVariableDialog"
			:showVariableDialog="showVariableDialog"
			:variableSelect="variableSelectIndex"
			:showDetail="showDetail"
			@cancel="closeVariable"
			@ok="sureVariable"
		/>
	</div>
</template>

<script>
import _ from 'lodash';
import VideoTable from '@/views/components/VideoTable.vue';
import AnswerNlu from '../../Answering/index.vue';

import SettingQuestion from './SettingQuestion.vue';
import UserAttribute from '../AiTemplateView/UserAttribute.vue';
import TemplateForm from './TemplateForm.vue';
import AiTemplateTitle from './AiTemplateTitle.vue';

import AssociatedVariableTable from '@/views/components/AssociatedVariableTable.vue';

import { getAiQuestion, getAgentInfo, getVariablesAll, getIntentLibaryList, getIntentDotList } from '@/api/api.js';
import AIWorkflow from '@/modules/workFlow';
import { insertStr } from '@/utils/tool';
import { getChangedNextStepWithType } from '../../../modules/nextstep/index';
import { getTitle, getGroupByBranches } from '@bpmn/utility/utility';

import { mapGetters, mapState } from 'vuex';

export default {
	props: {
		taskId: {
			type: String,
			default: () => '',
			required: true
		},
		showTemplate: {
			type: Boolean,
			default: () => false
		},
		workstep: {
			type: Object,
			default: () => {}
		}
	},

	computed: {
		...mapState('workflow', ['worksteps']),
		...mapGetters('workflow', ['messageSummarySource']),
		hasAiSpeak() {
			return AIWorkflow.hasAiSpeak(this.taskId);
		},
		hasWordsYes() {
			return AIWorkflow.hasWordsYes(this.taskId);
		},
		hasWaitTime() {
			return AIWorkflow.hasWaitTime(this.taskId);
		},
		hasConfidence() {
			return AIWorkflow.hasConfidence(this.taskId);
		},

		hasNextStep() {
			return AIWorkflow.hasNextStep(this.taskId);
		},
		hasNextStepNo() {
			return AIWorkflow.hasNextStepNo(this.taskId);
		},
		hasWordsOther() {
			return AIWorkflow.hasWordsOther(this.taskId);
		},
		hasWordsNoAnswer() {
			return AIWorkflow.hasWordsNoAnswer(this.taskId);
		},
		hasAiSpeakTextArea() {
			return AIWorkflow.hasAiSpeakTextArea(this.taskId);
		},
		hasEndTemplate() {
			return AIWorkflow.hasEndTemplate(this.taskId);
		},
		hasAiProcessSpeech() {
			// 实时拟合模式下，支持智能问答
			const { videoType } = AIWorkflow.getRobotProperty();
			return AIWorkflow.hasAiProcessSpeech(this.taskId) && videoType === 'real-time-fitting';
		},
		hasWordsIntention() {
			return AIWorkflow.hasWordsIntention(this.taskId);
		},
		hasWordsVariableJudge() {
			return AIWorkflow.hasWordsVariableJudge(this.taskId);
		},
		hasWordsInterfaceSelect() {
			return AIWorkflow.hasWordsInterfaceSelect(this.taskId);
		},
		hasWordsVariable() {
			return AIWorkflow.hasWordsVariable(this.taskId);
		},
		getAnswerTitleLabel() {
			return AIWorkflow.getAnswerTitleLabel(this.taskId);
		},
		getSettingVisiable() {
			return AIWorkflow.getSettingVisiable(this.taskId);
		},
		hasOtherWaitTime() {
			return AIWorkflow.hasOtherWaitTime(this.taskId);
		},
		hasCollectionResultSelect() {
			return AIWorkflow.hasCollectionResultSelect(this.taskId);
		},

		hiddenInnerContent() {
			const id = AIWorkflow.getTalkId(this.taskId);
			return ['hangup', 'speakWaiting', 'sendMessage', 'transfer', 'sceneTransfer', 'silentWating', 'messageSummary', 'sendContents'].indexOf(id) === -1;
		},

		onlyHasNextStep() {
			const id = AIWorkflow.getTalkId(this.taskId);
			return ['optionJudge', 'variableJudge', 'inviteHumanThreeParties', 'startSystemRecording', 'stopSystemRecording'].indexOf(id) !== -1;
		},

		hasInnerAiSpeakTextArea() {
			const id = AIWorkflow.getTalkId(this.taskId);
			return ['ivvr'].indexOf(id) !== -1;
		},
		hasBusinessInstruct() {
			return AIWorkflow.hasBusinessInstruct(this.taskId);
		},
		hasMultipleSelect() {
			return AIWorkflow.hasMultipleSelect(this.taskId);
		},

		getTalkId() {
			return AIWorkflow.getTalkId(this.taskId);
		},
		hasWordsOptionJudge() {
			return AIWorkflow.hasWordsOptionJudge(this.taskId);
		},
		hasWordsSendContents() {
			return AIWorkflow.hasWordsSendContents(this.taskId);
		},
		hasNlpBranch() {
			return AIWorkflow.hasNlpBranch(this.taskId);
		},
		hasNoAnswerOverTime() {
			return AIWorkflow.hasNoAnswerOverTime(this.taskId);
		},
		hasAiSpeakRequired() {
			return AIWorkflow.getTalkId(this.taskId) !== 'messageCollect';
		}
	},
	components: {
		VideoTable,
		AnswerNlu,
		UserAttribute,
		SettingQuestion,
		TemplateForm,
		AiTemplateTitle,
		AssociatedVariableTable
	},
	watch: {
		property: {
			handler(newVal, oldVal) {
				console.log(newVal, oldVal);
				this.form = newVal;
			},
			deep: true
		},
		taskId: {
			handler(newVal, oldVal) {
				if (newVal !== oldVal) {
					this.$nextTick(() => {
						this.init();
					});
				}
			},
			deep: true,
			immediate: true
		}
	},
	mounted() {
		this.init();
	},
	data() {
		return {
			videoType: '',
			audioType: '',
			form: {},
			rules: AIWorkflow.getTemplateValidateRules(this.taskId),
			nextStepYesPrevious: '',
			nextStepNoPrevious: '',
			nextStepOtherPrevious: '',
			nextStepNoAnswerPrevious: '',
			repeatAnswersPrevious: '',
			blurAnswersPrevious: '',
			resultFailedNextStepPrevious: '',
			recognizeFailedNextStepPrevious: '', // llm识别失败上一次编辑的下一步

			isShowUserAttribute: false,
			tableVideoDialog: false,
			tableVideoType: '',
			currentVariableInput: null,
			currentVideoInput: null,
			isShowAnswerNlu: false, // NLU 弹窗
			answerNluMode: '', // NLU 模式
			nluProp: '', // NLU 类型属性
			questionPages: {
				total: 0,
				pageSzie: 10,
				page: 1
			},
			showQuestionSetting: false,
			typeSelect: 'sendDeposition',
			judgeOptionsPrevious: [],
			nlpOptionsPrevious: [],
			ivvrOptionsPrevious: [],
			llmOptionsPrevious: [], // llm意图点列表编辑前内容
			ivvrOptionsVideo: [],
			variableJudgeOptionsPrevious: [],
			showDetail: AIWorkflow.isDetail,

			arrayVideoIdx: null, // 动态添加类型 Video 索引
			selectVideoIndex: [],

			showVariableDialog: false, // 关联变量弹窗
			variableSelectIndex: null, // 关联变量回显索引
			agentNameError: false, // 无效坐席ID
			variablesList: [], // 变量列表
			returnParametersError: false, // 请添加返回参数校验文案
			nluError: false, // NLU 弹窗错误提示
			intentLib: [], // 意图库列表
			intentLibName: '',
			requestParametersError: false, // 请添加请求参数校验文案

			insertStr: ''
		};
	},

	methods: {
		getTypeSelected() {
			this.typeSelect = AIWorkflow.getTalkId(this.taskId);
		},
		initPreNextStep() {
			const {
				nextStepYes,
				nextStepNo,
				nextStepOther,
				nextStepNoAnswer,
				resultFailedNextStep,
				judgeOptions,
				nlpOptions,
				ivvrOptions,
				variableJudgeOptions,
				repeatAnswers,
				blurAnswers,
				llmRecognizeNextStep,
				intentPoints
			} = this.form;
			this.nextStepYesPrevious = nextStepYes;
			this.nextStepNoPrevious = nextStepNo;
			this.nextStepOtherPrevious = nextStepOther;
			this.nextStepNoAnswerPrevious = nextStepNoAnswer;
			this.resultFailedNextStepPrevious = resultFailedNextStep;
			this.recognizeFailedNextStepPrevious = llmRecognizeNextStep;
			this.blurAnswersPrevious = null || blurAnswers[0].nextStep;
			this.repeatAnswersPrevious = null || repeatAnswers[0].nextStep;
			this.judgeOptionsPrevious = [];
			judgeOptions.map(item => {
				if (item.option) {
					this.judgeOptionsPrevious.push({ ...item });
				}
			});
			this.nlpOptionsPrevious = _.cloneDeep(nlpOptions);
			this.ivvrOptionsPrevious = _.cloneDeep(ivvrOptions);
			this.llmOptionsPrevious = _.cloneDeep(intentPoints);
			this.variableJudgeOptionsPrevious = _.cloneDeep(variableJudgeOptions);
		},
		input(prop, e) {
			if (prop === 'aiProcessSpeech') {
				const { mainProcessSpeech = null } = e;
				this.form.aiProcessSpeech = AIWorkflow.replaceInputValue(prop, mainProcessSpeech);
				this.form.intelligentReply = e;
				return;
			}

			this.form[prop] = AIWorkflow.replaceInputValue(prop, e);
			if (prop === 'collectShortVideoTime') {
				this.form['waitTime'] = AIWorkflow.replaceInputValue(prop, e * 3);
			}

			// console.warn(this.form[prop], this.form.summary, this.form);
			console.log(prop, 'index => input', e, this.form);

			//
			if (prop === 'responseBody' && e.length > 0) {
				this.returnParametersError = false;
			}
			if (prop === 'requestBody' && e.length > 0) {
				this.requestParametersError = false;
			}
		},

		onChange(prop, e) {
			if (prop === 'skillGroup') {
				this.form[prop] = [...e];
			} else {
				this.form[prop] = e;
			}

			console.log('change:', this.form, prop, e);
		},

		/** 下载NLP */
		downloadNluKeys(libType, point) {
			AIWorkflow.downloadNluKeys(libType, point);
		},

		onAddVariable(val, data) {
			this.currentVariableInput = val;
			this.isShowUserAttribute = true;
			console.log(data);
		},

		sureVideoData(selectedId, selected) {
			console.log('sureVideoData ', selectedId, selected, this.currentVideoInput, this.form);
			if (this.currentVideoInput !== 'ivvrOptions') {
				this.form[`${this.currentVideoInput}`] = selected;
			} else {
				this.ivvrOptionsVideo[this.arrayVideoIdx] = selected;
			}

			this.tableVideoDialog = false;
			this.selectVideoIndex[this.arrayVideoIdx] = selectedId;
		},
		clearVideo(prop) {
			if (this.prop !== 'ivvrOptions') {
				this.form[`${prop}`] = null;
			} else {
				this.ivvrOptionsVideo[this.arrayVideoIdx] = null;
			}
			this.selectVideoIndex[this.arrayVideoIdx] = '';
		},
		cancelVideoData() {
			this.tableVideoDialog = false;
		},
		onCloseUserAttribute() {
			this.isShowUserAttribute = false;
		},

		// 变量插入
		onChosseUserAttribute(data, businessData) {
			console.log(this.currentVariableInput, data, businessData);
			if (data && data.name) {
				// 客户信息_角色名_变量名
				if (this.currentVariableInput === 'aiProcessSpeech') {
					const wordsDom = document.getElementById(this.currentVariableInput);
					this.form['intelligentReply']['mainProcessSpeech'] = insertStr(this.form[this.currentVariableInput], wordsDom, this.formatVariable(data.name, data.id));
					this.form[this.currentVariableInput] = insertStr(this.form[this.currentVariableInput], wordsDom, this.formatVariable(data.name, data.id));
				} else {
					let wordsDom = document.getElementById(this.currentVariableInput);
					if (!wordsDom) {
						wordsDom = document.getElementById(this.currentVariableInput + 'textarea');
					}
					this.form[this.currentVariableInput] = insertStr(this.form[this.currentVariableInput], wordsDom, this.formatVariable(data.name, data.id));
					console.log(this.form[this.currentVariableInput], wordsDom, businessData);
				}
				this.saveVariableInProperty(data);
			}
			if (businessData && businessData.name) {
				// 业务信息_变量名
				if (this.currentVariableInput === 'aiProcessSpeech') {
					const wordsDom = document.getElementById(this.currentVariableInput);
					this.form['intelligentReply']['mainProcessSpeech'] = insertStr(this.form[this.currentVariableInput], wordsDom, this.formatVariable(businessData.name, businessData.id));
					this.form[this.currentVariableInput] = insertStr(this.form[this.currentVariableInput], wordsDom, this.formatVariable(businessData.name, businessData.id));
				} else {
					let wordsDom = document.getElementById(this.currentVariableInput);
					if (!wordsDom) {
						wordsDom = document.getElementById(this.currentVariableInput + 'textarea');
					}
					this.form[this.currentVariableInput] = insertStr(this.form[this.currentVariableInput], wordsDom, this.formatVariable(businessData.name, businessData.id));
					console.warn(this.form[this.currentVariableInput], wordsDom, businessData);
				}
				this.saveVariableInProperty(businessData);
			}

			this.isShowUserAttribute = false;
		},

		/** 下一步操作 */
		getChangedNextStep(subType = '') {
			let nodeType = AIWorkflow.getTalkId(this.taskId);
			const preNext = {
				yes: this.nextStepYesPrevious,
				no: this.nextStepNoPrevious,
				other: this.nextStepOtherPrevious,
				noAnswer: this.nextStepNoAnswerPrevious,
				unrecognized: this.resultFailedNextStepPrevious,
				recognizedFailed: this.recognizeFailedNextStepPrevious // llm识别失败
			};
			const curNext = {
				yes: this.form.nextStepYes,
				no: this.form.nextStepNo,
				other: this.form.nextStepOther,
				noAnswer: this.form.nextStepNoAnswer,
				unrecognized: this.form.resultFailedNextStep,
				recognizedFailed: this.form.llmRecognizeNextStep // llm识别失败
			};
			// 意图 | 选项 | 变量
			let preList = [];
			let curList = [];
			if (this.taskId.includes('ivvr') && (this.ivvrOptionsPrevious.length > 0 || this.form.ivvrOptions.length > 0)) {
				preList = this.ivvrOptionsPrevious;
				curList = this.form.ivvrOptions;
			}
			if (this.taskId.includes('variableJudge') && (this.variableJudgeOptionsPrevious.length > 0 || this.form.variableJudgeOptions.length > 0)) {
				preList = this.variableJudgeOptionsPrevious;
				curList = this.form.variableJudgeOptions;
			}
			if (this.taskId.includes('nlp') && (this.nlpOptionsPrevious.length > 0 || this.form.nlpOptions.length > 0)) {
				preList = this.nlpOptionsPrevious;
				curList = this.form.nlpOptions;
			}
			if (this.taskId.includes('optionJudge') && (this.judgeOptionsPrevious.length > 0 || this.form.judgeOptions.length > 0)) {
				preList = this.judgeOptionsPrevious;
				curList = this.form.judgeOptions;
			}

			if (this.taskId.includes('messageSure')) {
				preNext.repeat = this.repeatAnswersPrevious;
				curNext.repeat = null || this.form.repeatAnswers[0].nextStep;
				preNext.fuzzy = this.blurAnswersPrevious;
				curNext.fuzzy = null || this.form.blurAnswers[0].nextStep;
			}
			// llm意图识别，下一步更新
			if (this.taskId.includes('llm') && (this.llmOptionsPrevious.length > 0 || this.form.intentPoints.length > 0)) {
				preList = this.llmOptionsPrevious;
				curList = this.form.intentPoints;
			}

			if (subType === 'sendContents' || nodeType === 'sendContents') {
				nodeType = this.form.wordsSendContents.type;
			} else if (subType === 'sendMessage' || nodeType === 'sendMessage') {
				nodeType = 'screenSnapshot';
			}
			console.log('getChangedNextStep: ', preList, curList, nodeType, preNext, curNext);

			return getChangedNextStepWithType(subType || nodeType, preNext, curNext, preList, curList);
		},

		chooseUserAttribute(prop, data, businessData) {
			if (!this.form.wordsSendContents.wordsVariables) {
				this.form.wordsSendContents.wordsVariables = [];
			}
			if (data) {
				this.form.wordsSendContents.wordsVariables.push({ ...data });
				this.form.wordsSendContents.wordsVariableId = data.id;
			}
			if (businessData) {
				this.form.wordsSendContents.wordsVariables.push({ ...businessData });
				this.form.wordsSendContents.wordsVariableId = businessData.id;
			}
		},

		/** 存储用户选择的变量 */
		saveVariableInProperty(data) {
			console.log('saveVariableInProperty:', data);
			// AI 播报变量存储
			if (this.currentVariableInput === 'aiSpeak') {
				if (!this.form.aiSpeakVariables) {
					this.form.aiSpeakVariables = [];
				}
				// this.form.aiSpeakVariables.push({ ...data });
				this.form.aiSpeakVariableId = data.id;
				this.form.aiSpeakVariables.push(data.id);
				console.warn(this.form.aiSpeakVariables, 'aiSpeakVariables');
			}
			// 智能问答AI说变量存储
			if (this.currentVariableInput === 'aiProcessSpeech') {
				if (!this.form.aiProcessSpeechVariables) {
					this.form.aiProcessSpeechVariables = [];
				}
				this.form.aiProcessSpeechVariables.push(data.id);
				this.form.aiProcessSpeechVariableId = data.id;
			}
			// 肯定回答AI说变量存储
			if (this.currentVariableInput === 'wordsYes') {
				if (!this.form.wordsYesVariables) {
					this.form.wordsYesVariables = [];
				}
				this.form.wordsYesVariables.push(data.id);
				this.form.wordsYesVariableId = data.id;
			}
			// 否定回答AI说变量存储
			if (this.currentVariableInput === 'wordsNo') {
				if (!this.form.wordsNoVariables) {
					this.form.wordsNoVariables = [];
				}
				this.form.wordsNoVariables.push(data.id);
				this.form.wordsNoVariableId = data.id;
			}
			// 其他回答AI说变量存储
			if (this.currentVariableInput === 'wordsOther') {
				if (!this.form.wordsOtherVariables) {
					this.form.wordsOtherVariables = [];
				}
				this.form.wordsOtherVariables.push(data.id);
				this.form.wordsOtherVariableId = data.id;
			}
			// 最大次数AI说变量存储
			if (this.currentVariableInput === 'wordsEnd') {
				if (!this.form.wordsEndVariables) {
					this.form.wordsEndVariables = [];
				}
				this.form.wordsEndVariables.push(data.id);
				this.form.wordsEndVariableId = data.id;
			}
			// 不回答AI说变量存储
			if (this.currentVariableInput === 'wordsNoAnswer') {
				if (!this.form.wordsNoAnswerVariables) {
					this.form.wordsNoAnswerVariables = [];
				}
				this.form.wordsNoAnswerVariables.push(data.id);
				this.form.wordsNoAnswerVariableId = data.id;
			}
			// 不回答最大次数AI说变量存储
			if (this.currentVariableInput === 'wordsEndNoAnswer') {
				if (!this.form.wordsEndNoAnswerVariables) {
					this.form.wordsEndNoAnswerVariables = [];
				}
				this.form.wordsEndNoAnswerVariables.push(data.id);
				this.form.wordsEndNoAnswerVariableId = data.id;
			}
		},
		/** nlp 相关 */
		// 肯定回答设置
		settingClick(type, prop) {
			console.log(type, prop);
			this.answerNluMode = type;
			this.nluProp = prop;
			this.isShowAnswerNlu = true;
		},
		closeAnserNlu() {
			this.isShowAnswerNlu = false;
		},
		onAnswerYes() {
			console.log(this.form);
			this.isShowAnswerYes = true;
			this.showAnswerYes = true;
		},
		// 关闭肯定回答对话框
		answerClose() {
			this.isShowAnswerYes = false;
		},
		// 否定回答设置
		onAnswerNegative() {
			console.log(this.form.answerNoData);
			this.isShowAnswerNegative = true;
			this.showAnswerNegative = true;
		},
		// 关闭否定回答设置
		answerNegativeClose() {
			this.isShowAnswerNegative = false;
		},
		questionClose() {
			this.showQuestionSetting = false;
		},
		questionClick() {
			console.log(this.isActiveQuestion);
			if (this.isActiveQuestion) {
				this.stopConfirm();
			} else {
				this.isActiveQuestion = true;
			}
		},

		saveCheckQuestion(data) {
			this.form.intelligentReply.data = [...data];
			this.showQuestionSetting = false;
		},

		// 分页数据
		changePageSize(val) {
			this.questionPages.pageSzie = val;
			this.onSettingQuestion();
		},
		changeCurrentPage(val) {
			this.questionPages.page = val;
			this.onSettingQuestion();
		},

		// 提交肯定回答
		submitNluKeys() {
			this.isShowAnswerNlu = false;
		},

		// 智能问答
		onSettingQuestion() {
			let editBusinessId = this.$route.params.id || this.$route.query.id;
			let intelligentReplies = this.form.intelligentReply.data || [];
			getAiQuestion(editBusinessId, this.questionPages.page, this.questionPages.pageSzie, 'true')
				.then(res => {
					this.questionData = res.data.data;
					this.questionPages.total = res.data.count;
					this.showQuestionSetting = true;
				})
				.then(() => {
					this.questionData.forEach(item => {
						intelligentReplies.map(current => {
							if (item.name === current.name) {
								console.log(this.$refs.settingQuestion);
								this.$refs.settingQuestion.$refs.tableData.toggleRowSelection(item, true);
							}
						});
					});
				})
				.catch(err => {
					this.$message.error('获取智能问答数据失败');
					console.log('get AiQuestion error', err);
				});
		},

		save() {
			let data = null;
			let flag = false;
			this.$refs['aiTemplateTitle'].$refs['templateTitle'].validate(valid => {
				console.log('templateTitle validate result ', valid);
				if (valid) {
					flag = true;
				} else {
					console.log('aiTemplateTitle submit!!');
					return;
				}
			});
			this.$refs['templateForm'].$refs['template'].validate(valid => {
				console.log('template validate result ', valid, flag);
				if (flag && this.checkedVideoProperty() && valid) {
					data = this.filterSaveData();
				} else {
					console.log('error submit!!');
					return;
				}
			});

			// update talks
			this.$nextTick(() => {
				AIWorkflow.setTalks(this.worksteps);
			});
			return data;
		},
		async onOk() {
			let node = this.save();
			// 校验接口调用模板 ：请求参数，返回参数
			if (this.taskId.includes('interfaceCall')) {
				this.returnParametersError = false;
				this.requestParametersError = false;
				if (['put', 'post'].includes(this.form.callMethod)) {
					if (this.form?.requestBody.length === 0) {
						this.requestParametersError = true;
					}
					if (this.form?.responseBody.length === 0) {
						this.returnParametersError = true;
					}
					if (this.requestParametersError || this.returnParametersError) {
						return;
					}
				} else if (this.form.callMethod === 'get') {
					if (this.form?.responseBody.length === 0) {
						this.returnParametersError = true;
						return;
					}
				} else if (this.form.callMethod === 'delete') {
					if (this.form?.requestBody.length === 0) {
						this.requestParametersError = true;
						return;
					}
				}
			}

			console.log('save', node, this.form);
			this.agentNameError = '';
			// 邀请三方，校验坐席ID isDisabled: "N" isRobot: false
			if (node?.do?.data?.data?.data?.agentName) {
				try {
					const agentInfo = await getAgentInfo(node?.do?.data?.data?.data?.agentName);
					const { isDisabled, isRobot } = agentInfo.data;
					if (isRobot || isDisabled !== 'N') {
						console.warn('agent info : ', isDisabled, isRobot);
						this.agentNameError = '请填写正确人工坐席工号';
						return;
					}
				} catch (error) {
					this.agentNameError = '请填写正确人工坐席工号';
					return;
				}
			}
			const chagedNextSteps = this.getChangedNextStep();
			if (node) {
				this.$emit('onOk', { data: node, chagedNextSteps: chagedNextSteps });
			}
		},

		onClose() {
			this.$emit('onClose');
		},
		validateSummary() {
			let arr = this.form.summary.map(item => item.node);
			let result = getGroupByBranches(this.workflow.worksteps, this.workflow.startNode, arr, this.taskId);
			let branches = [];
			console.log(result, this.workflow, arr);
			if (result.length > 1) {
				branches.push({ id: this.taskId, name: getTitle(this.taskId, true), branch: result });
				this.branchTips(getTitle(this.taskId, true), result.length);
			}
		},
		// 分支提示
		branchTips(title, num) {
			setTimeout(() => {
				this.$message({
					message: `AI流程 <${title}> 中存在 ${num} 条流程分支，系统仅执行其中一个流程！`,
					type: 'warning'
				});
			}, 100);
		},

		filterSaveData() {
			console.log('form info', this.form, 'taskId', this.taskId);
			/** 字符串转数值 */
			let keys = Object.keys(this.form);
			keys.map(key => {
				if (AIWorkflow.getNumberTypeProperty(key)) {
					this.form[key] = Number(this.form[key]);
				}
				if (this.form.repeatAnswers[0].wordsTimesMax) {
					this.form.repeatAnswers[0].wordsTimesMax = Number(this.form.repeatAnswers[0].wordsTimesMax);
				}
				if (this.form.blurAnswers[0].wordsTimesMax) {
					this.form.blurAnswers[0].wordsTimesMax = Number(this.form.blurAnswers[0].wordsTimesMax);
				}
			});

			return AIWorkflow.filterTemplateTalkProperty(this.taskId, this.form);
		},

		checkedVideoProperty() {
			const { videoType, audioType } = AIWorkflow.getRobotProperty();
			if (videoType === 'pre-recorded-video' && audioType === 'video-native') {
				const ignore = [
					'messageCollect',
					'detectLivingFace',
					'sendMessage',
					'transfer',
					'sceneTransfer',
					'silentWating',
					'optionJudge',
					'messageSummary',
					'sendContents',
					'nlp',
					'soundReception',
					'variableJudge',
					'hangup',
					'inviteHumanThreeParties',
					'interfaceCall',
					'startSystemRecording',
					'stopSystemRecording'
				];
				if (!this.form['aiSpeakVideo'] && ignore.indexOf(AIWorkflow.getTalkId(this.taskId)) === -1) {
					this.aiSpeakVideoIcon = this.errorVideo;
					return false;
				}
			} else if (videoType === 'pre-recorded-video' && audioType === 'tts') {
				const ignore = [
					'messageCollect',
					'detectLivingFace',
					'sendMessage',
					'transfer',
					'sceneTransfer',
					'silentWating',
					'optionJudge',
					'messageSummary',
					'sendContents',
					'nlp',
					'soundReception',
					'variableJudge',
					'hangup',
					'inviteHumanThreeParties',
					'interfaceCall',
					'startSystemRecording',
					'stopSystemRecording'
				];
				if (!this.form['aiSpeakVideo'] && ignore.indexOf(AIWorkflow.getTalkId(this.taskId)) === -1) {
					this.aiSpeakVideoIcon = this.errorVideo;
					return false;
				}
				if (!this.form['wordsYesVideo'] && this.form['wordsYes']) {
					this.wordsYesVideoIcon = this.errorVideo;
					return false;
				}
				if (!this.form['wordsNoVideo'] && this.form['wordsNo']) {
					this.wordsNoVideoIcon = this.errorVideo;
					return false;
				}
				if (!this.form['wordsOtherVideo'] && this.form['wordsOther']) {
					this.wordsOtherVideoIcon = this.errorVideo;
					return false;
				}

				if (!this.form['wordsEndVideo'] && this.form['wordsEnd']) {
					this.wordsEndVideoIcon = this.errorVideo;
					return false;
				}

				if (!this.form['wordsNoAnswerVideo'] && this.form['wordsNoAnswer']) {
					this.wordsNoAnswerVideoIcon = this.errorVideo;
					return false;
				}

				if (!this.form['wordsEndNoAnswerVideo'] && this.form['wordsEndNoAnswer']) {
					this.wordsEndNoAnswerVideoIcon = this.errorVideo;
					return false;
				}
				return true;
			}
			if (this.form['aiSpeakVideo'] && audioType === 'native-video') {
				if (!this.form.aiSpeak) {
					this.form.aiSpeak = '播报视频:' + this.form['aiSpeakVideo'].fileName;
				}
			}
			return true;
		},

		showVideoTable(prop) {
			console.log(prop);
			this.currentVideoInput = prop;
			this.arrayVideoIdx = prop;
			this.tableVideoDialog = true;
		},
		// 设置推送的节点
		selectMultipleItem(value) {
			console.log('@@###selectMultipleItem', value);
			this.form.summary = value;
		},
		// 设置变量推送的变量
		selectVariableItem(value) {
			console.log('@@###selectVariableItem', value);
			this.form.wordsVariable = value;
		},
		//关联变量的取消，确定事件
		onAssociatedVariableClick() {
			if (this.form.associatedVariable.id) {
				this.variableSelectIndex = Number(this.form.associatedVariable.id);
			}
			this.showVariableDialog = true;
		},
		updateTitleName(name) {
			this.form.name = name;
		},
		// 取消关联变量
		closeVariable() {
			this.showVariableDialog = false;
		},
		// 确认关联变量
		sureVariable(key, data) {
			// console.log(data, '确认关联变量');
			const { id, roleId, variableName, initializationMode, linkedKey, variableType, url, method, params, dataMasking } = data;
			this.showVariableDialog = false;
			this.form.associatedVariable = {
				id,
				name: variableName,
				linkedKey: linkedKey,
				roleId: roleId,
				initMode: initializationMode === '随路数据' ? 'user-data' : initializationMode === 'API获取' ? 'api-data' : 'non-init',
				type: variableType === '数值' ? 'numeric' : variableType === '文本/字符串' ? 'text' : 'numericString',
				url: url ? url : '',
				method: method ? method : '',
				params: params ? params : [],
				dataMasking: dataMasking ? dataMasking : {}
			};
			console.log(key, data);
			console.log(this.form.associatedVariable, '关联变量', this.form);
		},

		// 下载 NLU
		downNlu() {},
		// 初始化所有角色
		getVariablesAll() {
			const sceneId = JSON.parse(sessionStorage.getItem('sceneData'))?.id;
			let param = {
				scenId: sceneId,
				page: 1,
				pageSize: 10000
			};
			getVariablesAll(param)
				.then(res => {
					this.variablesList = res.data.data?.rows || [];
					// 非api-data的变量列表
					if (this.form.informationRushurlAddress) {
						this.filterApiRequestUrl();
					}
				})
				.catch(err => {
					console.log(err);
				});
		},
		// 根据变量名格式化
		// 业务信息 变量名
		// 客户信息_角色名_变量名
		formatVariable(name, id) {
			const variable = this.variablesList.find(item => item.id === id);
			if (variable) {
				return variable.bizscenario_role ? `{{客户信息_${variable.bizscenario_role.name}_${name}_${id}}}` : `{{业务信息_${name}_${id}}}`;
			} else {
				return `{{${name}_${id}}}`;
			}
		},
		// 获取意图库和意图点
		getIntentLib() {
			// 调用意图库接口
			getIntentLibaryList('ivvr', 1, 100)
				.then(res => {
					console.log(res.data);
					this.intentLib = res.data.intentlibs;
					this.intentLib.forEach(item => {
						this.intentLibName = item.intentlib;
					});
					// 调用意图点接口
					getIntentDotList(this.intentLibName, 1, 100)
						.then(response => {
							console.log(response.data);
						})
						.catch(err => {
							console.log('getIntentDotList function error', err);
						});
				})
				.catch(err => {
					console.log('getIntentLib function error', err);
				});
		},
		// 过滤接口请求URL中的变量
		filterApiRequestUrl() {
			if (this.form.informationRushurlAddress) {
				const matches = this.form.informationRushurlAddress.match(/\{{([^}]+)\}}/gm);
				if (matches?.length) {
					// 非api-data的变量列表
					const list = this.variablesList.filter(item => item.initMode !== 'api-data');
					const removed = [];
					matches.map(item => {
						if (!list.find(item2 => item2.name === item.split('_')[2] || item2.name === item.split('_')[1])) {
							removed.push(item);
						}
					});
					removed.map(item => {
						this.form.informationRushurlAddress = this.form.informationRushurlAddress.replaceAll(item, '');
					});
				}
			}
		},
		init() {
			if (localStorage.getItem('nluError') && localStorage.getItem('nluError') === '1') {
				this.nluError = true;
			}
			AIWorkflow.setTalks(this.worksteps);
			const { videoType, audioType } = AIWorkflow.getRobotProperty();
			const { nextStepOption, getTemplateTalkProperty } = AIWorkflow;
			this.videoType = videoType;
			this.audioType = audioType;
			const node = AIWorkflow.getTemplateNode(this.taskId);
			this.nextStepOption = nextStepOption;
			this.form = getTemplateTalkProperty();

			AIWorkflow.setTemplateTalkProperty(this.taskId, this.form, AIWorkflow.pushTemplateAnswer(this.taskId, this.workstep));
			console.warn('???:', AIWorkflow.pushTemplateAnswer(this.taskId, this.workstep));
			console.log('##open node', this.form, node, this.taskId);
			this.getTypeSelected();
			AIWorkflow.getChangeNextStep('', '', node);
			// 初始化下一步的值
			this.initPreNextStep();
			console.log(this.form.associatedVariable);
			if (this.form.associatedVariable && this.form.associatedVariable.id) {
				this.variableSelectIndex = Number(this.form.associatedVariable.id);
			}

			if (this.taskId.split('_')[0] === 'messageSummary') {
				// 获取最新的汇总数据
				this.form.summary = [...AIWorkflow.validateMessageSummary(AIWorkflow.setMessageSummarySource(this.taskId), this.taskId)];
				console.warn(this.form.notifyExternal, 9999);
			}

			console.warn('open node form && nextStepOption', this.form, nextStepOption);
			// this.showVariableDialog = true;

			this.getVariablesAll();
			this.getIntentLib();
		}
	}
};
</script>

<style lang="less">
@import '../styles/index.less';

.ai-template-view-wrapper {
	.el-drawer__wrapper {
		pointer-events: none;
	}
}

.ai-template-wrapper-container {
	padding: 10px;
	display: flex;
	flex-direction: column;
	text-align: left;
	pointer-events: auto;

	.el-form-item__label {
		padding: 0;
		text-align: left;
	}
	.el-form-item {
		margin-bottom: 16px;
	}
}
</style>

<style lang="less" scoped>
.ai-template-wrapper-container {
	.dialog-footer {
		margin-top: 10px;
	}
}
</style>
